var $;
layui.use(['form','layer','jquery','upload'],function(){
	var form = layui.form,
        upload = layui.upload,
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		$ = layui.jquery;

 	form.on("submit(addBanner)",function(){
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.post("/saveBanner",{
            id : $("input[name=bannerId]").val(),
            businessId : $("input[name=businessId]").val(),
            displayOrder : $("input[name=displayOrder]").val(),
            status : $("select[name=status]").val(),
            title : $("input[name=title]").val(),
            picUrl : $("input[name=picUrl]").val(),
        },function(res){
            top.layer.close(index);
            top.layer.msg(res.data.info);
            layer.closeAll("iframe");
            //刷新父页面
            parent.location.reload();
        });
        return false;
 	});


    upload.render({
        elem: '.thumbBox',
        url: '/file/save',
        method : "post",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
        	var fileId = res.data.fileId;
        	var url = "/file/get/" + fileId;
            $('.thumbImg').attr('src',url);
            $('.thumbBox').css("background","#fff");
            //文件URL
            $('input[name="picUrl"]').val(url);
        }
    });

    //初始化下拉选项（最好是最后来初始化）
    function initSelect(){
        $('select').each(function(index,element){
            var page = $(element).attr("data-page");
            var key = $(element).attr("data-key");
            var value = $(element).attr("data-value");
            $.get("/getDictByPageKey",{page:page,key:key}, function(result){
                if(result.msg === 'success'){
                    var items = result.data;
                    items.forEach(function(item){
                        $(element).append("<option value='" + item.value + "'>"+ item.name + "</option>")
                    });
                    if(value){
                        $(element).val(value);
                    }
                    form.render("select");
                }
            });
        });
    }
    //最后初始化下拉选项
    initSelect();
});

//格式化时间
function formatTime(_time){
    var year = _time.getFullYear();
    var month = _time.getMonth()+1<10 ? "0"+(_time.getMonth()+1) : _time.getMonth()+1;
    var day = _time.getDate()<10 ? "0"+_time.getDate() : _time.getDate();
    var hour = _time.getHours()<10 ? "0"+_time.getHours() : _time.getHours();
    var minute = _time.getMinutes()<10 ? "0"+_time.getMinutes() : _time.getMinutes();
    return year+"-"+month+"-"+day+" "+hour+":"+minute;
}


